package com.jlu.springsecurity.config;

import com.jlu.springsecurity.handler.MyAccessDeniedHandler;
import com.jlu.springsecurity.handler.MySuccessHander;
import com.jlu.springsecurity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;


@Configuration
public class WebConfig extends WebSecurityConfigurerAdapter{

  @Autowired
  private UserService userDetailsService;

  @Autowired
  private DataSource datasource;

  @Autowired
  private PersistentTokenRepository persistentTokenRepository;

  @Override
  protected void configure(HttpSecurity http) throws Exception {

    http.formLogin()
            .usernameParameter("name")
            .passwordParameter("password")
            .loginProcessingUrl("/login")
//            .loginPage("/login.html")
            .loginPage("/showLogin")
            .successForwardUrl("/toMain")
//            .successHandler(new MySuccessHander("/main.html"))
            .failureForwardUrl("/toError");

    http.authorizeRequests()
            .antMatchers("/error.html").permitAll()
            .antMatchers("/showLogin").permitAll()
            .antMatchers("/main1.html").hasAuthority("admin")
            .antMatchers("/main2.html").access("hasRole('abc')")
            .antMatchers("/main2.html").hasAuthority("admin")
            .antMatchers("/main1.html").hasIpAddress("127.0.0.1")
            .antMatchers("/demo").hasRole("abc")
            .anyRequest().authenticated();
//            .anyRequest().access("@myServiceImpl.hasPermission(request,authentication)");

//    http.csrf().disable();

    http.exceptionHandling()
            .accessDeniedHandler(new MyAccessDeniedHandler());

    http.rememberMe()
            .userDetailsService(userDetailsService)
            .tokenRepository(persistentTokenRepository)
            .tokenValiditySeconds(60);

    http.logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login.html");
  }

  @Bean
  public PersistentTokenRepository PersistentTokenRepository(){
    JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
    jdbcTokenRepository.setDataSource(datasource);
//    jdbcTokenRepository.setCreateTableOnStartup(true);
    return jdbcTokenRepository;
  }
}
